import { axios, storage } from 'g6-fn'

import { modelLibraryApi } from '@/services/api'
import { http } from '@/services/http'

export type FileObj = {
  file: File
  id: string
  status: 'wait' | 'uploading' | 'success' | 'error'
  address: string
  percent: number
  bucketId: string //数据集编号
  cancelToken?: any
}

const CancelToken /* 取消请求令牌 */ = axios.CancelToken

export const uploadApi = ({ file, onUploadProgress, modelBaseId }: any): Promise<any> => {
  return new Promise((resolve, reject) => {
    if (file.status !== 'wait') {
      reject('File status is not "wait"')
      return
    }

    file.status = 'uploading'

    const uploadFile = async () => {
      try {
        // const fileEnCodeName = encodeURIComponent(file.name)
        const fileEnCodeName = file.name

        // 获取minio地址
        const modelArr = [{ name: fileEnCodeName, type: file.name.split('.').pop() }]
        // console.log(modelArr, 'modelArr')

        const res = await modelLibraryApi.preUploadASingleFile(
          {
            modelInfoPresignedReqVoList: modelArr,
            modelBaseId
          },
          {
            isAddUid: true
          }
        )
        // console.log(res, 'uploadFile')

        const minioUrl = res.data[0].presignedUrl
        const minioUuid = res.data[0].uuid
        file.uuid = minioUuid
        const source = CancelToken.source()
        file.cancelToken = source
        const config = {
          timeout: 6000000, // 设置超时时长10min
          onUploadProgress,
          cancelToken: source.token
        }
        console.log(minioUrl, file, config, 'config111111111')

        // 发起文件上传请求
        await http.upload(minioUrl, file, config)

        file.status = 'success'
        const storedIds = storage.get('uploadModelFile') || []
        storedIds.push({ modelBaseId, list: [{ uuid: minioUuid, type: file.name.split('.').pop() }] })
        storage.set('uploadModelFile', storedIds)
        resolve('上传成功')
      } catch (error) {
        console.log('error', error)
        file.status = 'error'
        reject('上传失败')
      }
    }

    uploadFile()
  })
}
